<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">管理系统登录</h2>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="loginForm" :rules="loginRules" label-width="auto">
        <el-form-item label="账号" prop="username">
          <el-input v-model="loginForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="handleLogin(ruleFormRef)">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { login } from '../api/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const ruleFormRef = ref(null)
const loginForm = ref({
  username: '',
  password: ''
})
const loginRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

const handleLogin = async() => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      login(loginForm.value)
        .then(response => {
          localStorage.setItem('token', response.data.token)
          ElMessage.success('登录成功')
          router.push('/dashboard')
        }).catch(() => {
          loading.value = false
        })
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.login-card {
  width: 400px;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}

.login-btn {
  width: 100%;
}
</style>
